package com.zghhost.stockweb.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zghhost.stockweb.constans.SInaConstans;
import com.zghhost.stockweb.entity.SinaDadanEntity;
import com.zghhost.stockweb.pojo.DadanCommonData;
import com.zghhost.stockweb.pojo.StockDayInfo;
import com.zghhost.stockweb.service.impl.KLineService;
import com.zghhost.stockweb.service.impl.SinaDadanService;
import com.zghhost.stockweb.util.CalendarUtil;
import com.zghhost.stockweb.util.DateUtil;
import com.zghhost.stockweb.util.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * @author guohua.zhang@zhaopin.com.cn
 * @Date 2019/5/18 12:37
 */
@Controller
@RequestMapping("/dadan")
public class SinaDadan {
    private static Logger log = LoggerFactory.getLogger(SinaDadan.class);

    @Autowired
    SinaDadanService sinaDadanService;

    @Autowired
    KLineService kLineService;

    @RequestMapping
    public String index()throws Exception{
        return "dadan";
    }

    @RequestMapping("data")
    @ResponseBody
    public Object dadanData(String code)throws Exception{
        //默认查询过去30天
        Date edate = new Date();
        Date sdate = DateUtil.addDate(edate, Calendar.DATE,-30);
        String sday = DateUtil.parseDateToStr(sdate,DateUtil.DATE_FORMAT_YYYY_MM_DD);
        String eday = DateUtil.parseDateToStr(edate,DateUtil.DATE_FORMAT_YYYY_MM_DD);
        List<SinaDadanEntity> data = sinaDadanService.getDayRangeDadan(code,sday,eday);

        //计算平均数 400 800 1600 3200 6400
        Map<String, Map<String,Double[]>> dadanavg = new HashMap<>();
        data.stream().forEach(e -> {
            if("U".equals(e.getKind())){
                String day = e.getTicktime().substring(0,e.getTicktime().indexOf(" "));
                Long volume = e.getVolume();

                Map<String,Double[]> volumeMap;
                if((volumeMap = dadanavg.get(day)) == null){
                    dadanavg.put(day,(volumeMap = new HashMap<>()));
                }

                String volumekey = "";
                if (volume <= 800 * 100){
                    volumekey = "400";
                }else if (volume <= 1600 * 100){
                    volumekey = "800";
                }else if (volume <= 3200 * 100){
                    volumekey = "1600";
                }else if (volume <= 6400 * 100){
                    volumekey = "3200";
                }else{
                    volumekey = "6400";
                }

                Double[] totalvalue;
                if((totalvalue = volumeMap.get(volumekey)) == null){
                    volumeMap.put(volumekey,(totalvalue = new Double[]{0D,0D}));
                }

                totalvalue[0] = totalvalue[0]+e.getPrice();
                totalvalue[1] = totalvalue[1]+1;
            }
        });


        //查询k线
        String  klineCode = "";
        if(code.startsWith("sz")){
            klineCode = "1"+code.substring(2);
        }else{
            klineCode = "0"+code.substring(2);
        }

        String klsday = DateUtil.parseDateToStr(sdate,DateUtil.DATE_FORMAT_YYYYMMDD);
        String kleday = DateUtil.parseDateToStr(edate,DateUtil.DATE_FORMAT_YYYYMMDD);

        List<StockDayInfo> kline = kLineService.getKLine(klineCode,klsday,kleday);

        Object[][] sdata = new Object[kline.size()][6+5];

        for (int ic=kline.size()-1,i=ic; i >= 0; i--) {
            StockDayInfo k = kline.get(i);

            Map<String,Double[]> dayavg = dadanavg.get(k.getRiqi());
            if(dayavg != null){
                Double[] vol400 = dayavg.get("400");
                Double[] vol800 = dayavg.get("800");
                Double[] vol1600 = dayavg.get("1600");
                Double[] vol3200 = dayavg.get("3200");
                Double[] vol6400 = dayavg.get("6400");
                Double avgddprice400 = vol400 == null ? k.getZuidi() : vol400[0]/vol400[1];
                Double avgddprice800 = vol800 == null ? k.getZuidi() : vol800[0]/vol800[1];
                Double avgddprice1600 = vol1600 == null ? k.getZuidi() : vol1600[0]/vol1600[1];
                Double avgddprice3200 = vol3200 == null ? k.getZuidi() : vol3200[0]/vol3200[1];
                Double avgddprice6400 = vol6400 == null ? k.getZuidi() : vol6400[0]/vol6400[1];
                sdata[ic-i] = new Object[]{k.getRiqi(),k.getKaipan(),k.getShowpan(),k.getZuigao(),k.getZuidi(),k.getChengjiaoliang(),avgddprice400,avgddprice800,avgddprice1600,avgddprice3200,avgddprice6400};
            }else {
                sdata[ic-i] = new Object[]{k.getRiqi(),k.getKaipan(),k.getShowpan(),k.getZuigao(),k.getZuidi(),k.getChengjiaoliang(),k.getZuidi(),k.getZuidi(),k.getZuidi(),k.getZuidi(),k.getZuidi()};
            }
        }

//        DadanCommonData dadanCommonData = new DadanCommonData();
//        dadanCommonData.setKline(sdata);
//        dadanCommonData.setDadan(data);

        return sdata;
    }

    /**
     * 下载所有个股过去半个月的大单
     * @param sday
     * @param eday
     * @return
     * @throws Exception
     */
    @RequestMapping("down")
    @ResponseBody
    public Object down(@RequestParam(required = true) String sday,@RequestParam(required = true) String eday)throws Exception{
        new DownThread(sday,eday).start();
        return true;
    }

    class DownThread extends Thread{
        private String sday;
        private String eday;

        public DownThread(String sday,String eday){
            this.sday = sday;
            this.eday = eday;
        }

        SinaDadanService threadDadanService = new SinaDadanService();

        @Override
        public void run() {
            try{
                log.info("task start:"+sday+" -> "+eday);

                SinaDadanService sinaDadanService = new SinaDadanService();

                for(int i=0,ic=37;i<ic;i++){
                    String url = String.format(SInaConstans.ALL_GEGU,i+1);
                    log.info("beigin: "+url);
                    String resstr = HttpUtil.doHttpGet(url,"gb2312");
                    if(resstr != null && resstr.startsWith("[") && resstr.endsWith("]")){
                        JSONArray jarr = JSONArray.parseArray(resstr);
                        for(int j=0,jc=jarr.size();j<jc;j++){
                            JSONObject job = jarr.getJSONObject(j);
                            String symbol = job.getString("symbol");

                            threadDadanService.getDayRangeDadan(symbol,sday,eday);

                            Thread.sleep(3401);
                        }
                    }
                    log.info(""+(i+1)+" finash.");
                }
            }catch (Exception e){
                log.error("",e);
            }
        }
    }
}
